package com.ll.module_translate.model

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel2
import com.ll.module_translate.db
import com.ll.module_translate.entity.TransResult
import com.ll.module_translate.entity.isError
import com.ll.module_translate.entity.isSuccess
import com.ll.module_translate.insert
import com.ll.module_translate.repository.TranslateRepository
import com.ll.module_translate.utils.TransLanguage
import com.ll.module_translate.utils.TransLanguage.CToR
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author: ll
 * @CreateTime: 2021/10/29 15:10
 */
@ExperimentalCoroutinesApi
class TranslateModel : BaseViewModel2() {

    var transKind = CToR

    val query = MutableLiveData<TransResult>()

    private var transResult = TransResult()

    fun translateContent(
            value: String,from:String,to:String
    ) = launch {
        if (value.isNotEmpty())
            transResult = TransResult()
        TranslateRepository.translate(
                value,
                from,
                to
        ).apply {
            isSuccess { from, to, trans_result ->
                for (index in trans_result.indices) {
                    transResult.dst += trans_result[index].dst
                    transResult.src += trans_result[index].src
                }
                transResult.insert()
                query.postValue(transResult)
            }
            isError { _, error_msg ->
                transResult.dst = error_msg
                query.postValue(transResult)
            }
        }
    }




    val isLike = MutableStateFlow(false)

    fun getList() = isLike.transformLatest {
        emitAll(
            if (it)
                db.queryLikeList()
            else
                db.queryHistoryList()
        )
    }.asLiveData()

    fun getListDesc() = isLike.transformLatest {
        emitAll(
            if (it)
                db.queryLikeListDesc()
            else
                db.queryHistoryListDesc()
        )
    }.asLiveData()


    val history = MutableStateFlow(TransLanguage.CToR().first)
}